package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.framework.exception.ServiceException;
import com.mars.module.admin.entity.SysProvince;
import com.mars.module.admin.entity.SysScenicArea;
import com.mars.module.admin.entity.SysSpotTicket;
import com.mars.module.admin.mapper.SysSpotTicketMapper;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysOrderRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysOrderMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysOrder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单业务层处理
 *
 * @author mars
 * @date 2024-03-26
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysOrderServiceImpl implements ISysOrderService {

    private final SysOrderMapper baseMapper;
    private final SysSpotTicketMapper ticketMapper;
    private final SysUserMapper userMapper;
    private final ISysDictDataService iSysDictDataService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder add(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long userId = ContextUserInfoThreadHolder.get().getId();
        entity.setCreateById(userId);
        entity.setStatus("1");
        baseMapper.insert(entity);
        //判断用户余额是否足够
        SysUser sysUser = userMapper.selectById(userId);
        if (sysUser.getBalance() < request.getTotalPrice()) {
            throw new ServiceException("余额不足，请充值！");
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.updateById(entity);
        SysOrder order = baseMapper.selectById(request.getId());
        SysUser sysUser = userMapper.selectById(order.getUserId());
        if ("2".equals(request.getStatus())) {
            //已支付则更新用户余额
            sysUser.setBalance(sysUser.getBalance() - order.getTotalPrice());
        } else if ("3".equals(request.getStatus())) {
            //已支付则更新用户余额
            sysUser.setBalance(sysUser.getBalance() + order.getTotalPrice());
        }
        userMapper.updateById(sysUser);
        return true;
    }

    @Override
    public SysOrder getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysOrder> pageList(SysOrderRequest request) {
        Page<SysOrder> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        IPage<SysOrder> pageRecord = baseMapper.selectPage(page, query);
        List<SysOrder> records = pageRecord.getRecords();
        List<SysOrder> recordsNew = new ArrayList<>();
        for (SysOrder order : records) {
            SysSpotTicket sysSpotTicket = ticketMapper.selectById(order.getTicketId());
            SysUser sysUser = userMapper.selectById(order.getUserId());
            order.setTicketName(sysSpotTicket == null ? "" : sysSpotTicket.getName());
            order.setUserName(sysUser == null ? "" : sysUser.getUserName());
            order.setStatus(iSysDictDataService.getDictDataById("order_status", order.getStatus()));
            recordsNew.add(order);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysOrder> list(SysOrderRequest request) {
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysOrder> buildWrapper(SysOrderRequest param) {
        LambdaQueryWrapper<SysOrder> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.eq(SysOrder::getStatus, param.getStatus());
        }
        if (param.getAmount() != null) {
            query.eq(SysOrder::getAmount, param.getAmount());
        }
        if (param.getTotalPrice() != null) {
            query.eq(SysOrder::getTotalPrice, param.getTotalPrice());
        }
        if (param.getUserId() != null) {
            query.eq(SysOrder::getUserId, param.getUserId());
        }
        return query;
    }

}
